'use strict';

exports.main = async (event, context) => {
  console.log('【createSecurityNotification】云函数被调用，event：', event);

  const { 
    userId, 
    type, 
    details 
  } = event;

  try {
    let title = '';
    let content = '';
    let priority = 'normal';

    // 根据安全事件类型生成通知
    switch (type) {
      case 'login_location':
        title = '异地登录提醒';
        content = `检测到您的账号在${details.location}登录，如非本人操作请及时修改密码`;
        priority = 'high';
        break;
      case 'password_change':
        title = '密码修改成功';
        content = '您的账号密码已成功修改，如非本人操作请联系客服';
        priority = 'high';
        break;
      case 'account_locked':
        title = '账号异常锁定';
        content = '您的账号因异常操作被暂时锁定，请联系客服解锁';
        priority = 'urgent';
        break;
      case 'verification_success':
        title = '实名认证通过';
        content = '恭喜！您的实名认证已通过，现在可以享受更多功能';
        priority = 'normal';
        break;
      case 'verification_failed':
        title = '实名认证未通过';
        content = `实名认证未通过：${details.reason}，请重新提交认证材料`;
        priority = 'normal';
        break;
      default:
        return { success: false, message: '未知的安全事件类型' };
    }

    // 调用创建通知云函数
    const result = await uniCloud.callFunction({
      name: 'createNotification',
      data: {
        userId: userId,
        type: 'account_security',
        category: 'account',
        title: title,
        content: content,
        priority: priority,
        actionUrl: type === 'verification_failed' ? '/pages/user/verification' : '',
        actionText: type === 'verification_failed' ? '重新认证' : ''
      }
    });

    console.log('【createSecurityNotification】通知创建结果：', result);

    return result.result || result;

  } catch (e) {
    console.error('【createSecurityNotification】异常:', e);
    return { success: false, message: '安全通知创建失败：' + e.message };
  }
}; 